import React, { Component } from 'react';
import { Menu } from 'antd';
import { NavLink } from 'react-router-dom';
import { connect } from 'react-redux';
import { switchMenu } from './../../redux/action';
import MenuConfig from './../../config/menuConfig';
import './index.less';
const { SubMenu } = Menu;

class NavLeft extends Component {
	constructor(props){
		super(props);
		this.state={
			currentKey: ""
		}
	}
	handleClick = ({item,key}) => {
		console.log(item)
		console.log(item.props.title)
		this.props.changeTitle(key)
		this.setState({
			currentKey: key
		})
	}
	UNSAFE_componentWillMount(){
		const menuTreeNode = this.renderMenu(MenuConfig);
		let currentKey = window.location.hash.replace(/#|\?.*$/g,"");
		this.setState({
			currentKey,
			menuTreeNode
		})
	}
	//菜单渲染
	renderMenu = (data) => {
		return data.map((item, index)=>{
			if(item.children){
				return (
					<SubMenu title={item.title} key={item.key}>
						{ this.renderMenu(item.children) }
					</SubMenu>
				)
			}
			return <Menu.Item key={item.key}>
				<NavLink to={item.key}>{item.title}</NavLink>
			</Menu.Item>
		})
	}
	render(){
		return (
			<div>
				<div className="logo">
					<img src="/assets/logo-ant.svg" alt=""/>
					<h1>Imooc MS</h1>
				</div>
				<Menu
					theme="dark"
					selectedKeys={this.state.currentKey}
					onClick={this.handleClick}
				>
					{ this.state.menuTreeNode }
				</Menu>
			</div>
		)
	}
}

const mapDispatchToProps = (dispatch) => {
	return {
		changeTitle(val){
			console.log(val)
			dispatch(switchMenu(val));
			//上面这句等价如下
//			dispatch({
//				type: "SWITCH_MENU",
//				menuName: val
//			})
		}
	}
}
export default connect(null,mapDispatchToProps)(NavLeft);